<?php

class SiteController extends Controller {

    public $layout = "//layouts/masterpage";

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        $bookDataProvider = new CActiveDataProvider("Product", array(
                    'criteria' => array(
                        'order' => 'createdDate DESC',
                    ),
                    'pagination' => array(
                        'pageSize' => 4,
                    ),
                ));

        $allBooks = Product::model()->getAllProducts();
        $this->render('index', array(
            'allBooks' => $allBooks,
            'bookDataProvider' => $bookDataProvider,
        ));
    }

    public function actionBookByCategory() {
        $allMoviesByCat = array();

        if (isset($_GET['catId'])) {
            $catId = $_GET['catId'];

            $categoryName = ProductCategory::model()->findByPk($catId)->name;
        }
        $isCategorized = true;
//        $categoryName = Category::model()->getNameById($catId);
//        $this->render('index', array(
//            'allMovies' => $allMoviesByCat,
//            'movieDataProvider' => $movieDataProvider,
//            'isCategorized' => $isCategorized,
//            'categoryName' => $categoryName,
//        ));

        $bookDataProvider = new CActiveDataProvider("Product", array(
                    'criteria' => array(
                        'condition' => 'productCategoryId = ' . $catId,
                        'order' => 'createdDate DESC',
                    ),
                    'pagination' => array(
                        'pageSize' => 4,
                    ),
                ));

        $allBooks = Product::model()->getAllProducts();
        $this->render('index', array(
            'allBooks' => $allBooks,
            'bookDataProvider' => $bookDataProvider,
            'categoryName' => $categoryName,
            'isCategorized' => $isCategorized,
        ));
    }

    public function actionBook($id = null) {
        if ($id == null)
            $movies = Product::model()->findAll();

        $book = Product::model()->findByPk($id);

        Yii::app()->user->setReturnUrl(array('site/book', 'id' => $id));

        $comment = $this->newComment($book);

        $this->render('book', array(
            'book' => $book,
            'comment' => $comment,
        ));
    }

    protected function newComment($book) {
        $comment = new BookComment();
        if (isset($_POST['BookComment'])) {
            $comment->userId = Yii::app()->user->id;
            $comment->productId = $book->productId;
            $comment->content = $_POST['BookComment']['content'];
            if ($comment->save(false)) {
                Yii::app()->user->setFlash('commentSubmitted', 'Thank you');
//                $this->refresh();
                if (isset(Yii::app()->user->returnUrl))
                    $this->redirect(Yii::app()->user->returnUrl);
            }
        }
        return $comment;
    }

    public function actionCreateUser() {
        $model = new User;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if ($model->save())
                $this->redirect(array("site/index"));
        }

        $this->render('_userform', array(
            'model' => $model,
        ));
    }

    public function actionUpdateUser($userid = null) {
        if (isset($_GET['uid']))
            $model = User::model()->findByPk($_GET['uid']);

        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if ($model->save())
                $this->redirect(array('site/index'));
        }

        $this->render('_userform', array(
            'model' => $model,
        ));
    }

    public function actionRemoveFromCart() {
        if (isset($_GET['remove']) && (int) $_GET['remove'] > 0) {
            $productId = (int) $_GET['remove'];

            if (in_array($productId, Yii::app()->session['pids'])) {
                $position = array_search($productId, Yii::app()->session['pids']);
                unset($_SESSION['pids'][$position]);
                unset($_SESSION['pcounts'][$position]);

                Yii::app()->session['pids'] = array_values($_SESSION['pids']);
                Yii::app()->session['pcounts'] = array_values($_SESSION['pcounts']);

                $this->redirect(array('site/viewcart'));
            }
        }
        else
            throw new CHttpException("No suitable paramter");
    }

    public function actionClearCart() {
        //UNSET using Yii::app()->session for it to work
        unset(Yii::app()->session['pids']);
        unset(Yii::app()->session['pcounts']);

        $this->redirect(array('site/viewcart'));
    }

    public function actionAddToCart() {
        //TIPS
        //  USE Yii::app()->session to GET $_SESSION
        //      $_SESSION to SET $_SESSION


        if (isset($_GET['add2cart']) && (int) $_GET['add2cart'] > 0) {
            $productId = (int) $_GET['add2cart'];
            //check whether null product
            $product = Product::model()->findByPk($productId);
            if (is_null($product))
                throw new CHttpException("Invalid request product");

            //initialize sessions variable if not yet exist
            if (!isset(Yii::app()->session['pids'])) {
                Yii::app()->session['pids'] = array();
                Yii::app()->session['pcounts'] = array();
            }

            //if product already in cart
            if (in_array($productId, Yii::app()->session['pids'])) {
                $position = array_search($productId, Yii::app()->session['pids']);
//                    Yii::app()->session['pcounts'][$position] ++;
                $_SESSION['pcounts'][$position]++;
            } else {// add new item to cart
                $_SESSION['pids'][] = $productId;
                $_SESSION['pcounts'][] = 1;
            }

            $this->redirect(array('site/viewcart'));
        }
        else
            throw new CHttpException("No suitable paramter");
    }

    public function actionViewCart() {
        $cartItems = array();
        $cartQuantities = Yii::app()->session['pcounts'];

//        print_r($_POST);
        if (isset($_POST)) {//if update cart
            if (isset(Yii::app()->session['pids'])) {
                foreach (Yii::app()->session['pids'] as $key => $pid) {
                    //get quantity from each 
                    $q = intval($_POST['product' . $pid]);
                    //if valid q then proceed
                    if ($q > 0 && $q <= 999) {
                        $_SESSION['pcounts'][$key] = $q;
                    } else {
                        //message here: some products not updated because > 0 || < 999
                    }
                }
                //update $cartQuantities 
                $cartQuantities = Yii::app()->session['pcounts'];
            }
        }

        //populate cart items
        if (isset(Yii::app()->session['pids'])) {
            foreach (Yii::app()->session['pids'] as $pid) {
                $cartItems[] = Product::model()->findByPk($pid);
            }
        }

        $this->render('cart', array(
            'cartItems' => $cartItems,
            'cartQuantities' => $cartQuantities,
        ));
    }
    
    public function actionCheckout(){
        $model = new Order();
        
        if (isset($_POST['Order'])){
            $model->attributes=$_POST['Order'];
            
            $model->createDate = new CDbExpression('NOW()');
            
            if ($model->save()){
                //session
                $session = Yii::app()->session;
                $pids = $session['pids'];
                $pcounts = $session['pcounts'];
                
                //create associated shopping carts
                foreach ($pids as $key => $pid){
                    $product = Product::model()->findByPk($pid);
                    
                    $cart = new ShoppingCart();
                    $cart->productId = $pid;
                    $cart->orderId = $model->orderId;
                    $cart->name = $product->name;
                    $cart->price = $product->price;
                    $cart->quantity = $pcounts[$key];
                    
                    if ($cart->save()){
                        
                    }
                }
                //reset session shopping cart
                $this->redirect(array('site/clearcart'));
            }
        }
        
        $this->render('checkout', array(
            'model' => $model,
        ));
    }

    public function actionDeleteComment() {
//        if (Yii::app()->request->isPostRequest) {
        if (isset($_GET['cid'])) {
            // we only allow deletion via POST request
            $commentId = $_GET["cid"];

            $comment2Del = BookComment::model()->findByPk($commentId);

            $bookId = $comment2Del->productId;

            if (count($comment2Del) > 0) {
                // delete command by sql
                $deleteQuery = "DELETE FROM " . BookComment::model()->tableName() . "
                                WHERE commentId = :commentId";

                $command = Yii::app()->db->createCommand($deleteQuery);
                $command->bindValue(":commentId", $commentId, PDO::PARAM_INT);
                $command->query();

                $this->redirect(array("site/book", "id" => $bookId));
            } else {

                throw new CHttpException(400, 'Invalid request. Not any ID like that in database');
            }
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    public function actionCategory($id = null) {

        $this->render('index');
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $headers = "From: {$model->email}\r\nReply-To: {$model->email}";
                mail(Yii::app()->params['adminEmail'], $model->subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

}